package nancal.mp.db.mongo.entity.dev

import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import nbcp.base.comm.JsonMap
import nbcp.base.comm.StringMap
import nbcp.base.db.IdCodeName
import nbcp.base.db.IdName
import nbcp.base.db.KeyValueString
import nbcp.base.db.annotation.Cn
import nbcp.base.db.annotation.DbEntityGroup
import nbcp.base.extend.FromJson
import nbcp.base.extend.IfUntil
import nbcp.base.model.BaseMarkEntity
import nbcp.base.utils.CodeUtil
import org.slf4j.LoggerFactory
import org.springframework.data.mongodb.core.mapping.Document
import java.time.LocalDateTime

@Document
@DbEntityGroup("dev")
@Cn("Api故事")
open class ApiStory(
        var productLine: IdCodeName = IdCodeName(),
        var name: String = "",
        @Cn("api地址")
        var apiAddress: String = "",
        @Cn("Api")
        var apis: MutableList<ApiInstanceId> = mutableListOf(),

        @Cn("创建者")
        var createBy: IdName = IdName()
) : BaseMarkEntity() {
}


class KeyValueScript(
        key: String = "",
        value: String = "",
        @Cn("通过脚本获取")
        var script: String = ""
) : KeyValueString(key, value)


open class ApiInstanceId : ApiInstance() {
    var id = CodeUtil.getCode()
}

@JsonIgnoreProperties("responseJson")
open class ApiInstance(
        var apiDefine: ApiDefine = ApiDefine(),
        @Cn("参数")
        var parameters: List<KeyValueScript> = listOf(),
        var postBodyScript: String = "",
        var postBody: String = "",

        @Cn("状态码")
        var status: Int = 0,
        @Cn("响应头")
        var responseHeader: Map<String, String> = mapOf(),
        @Cn("响应体")
        var responseBody: String = "",

        var lastExecuteAt: LocalDateTime = LocalDateTime.now(),
        @Cn("备注")
        var remark: String = "",
) {
    val responseJson: JsonMap?
        get() {
            if (!this.status.IfUntil(200, 400)) {
                return null;
            }

            if (this.responseBody.isNullOrEmpty()) {
                return null;
            }

            try {
                return this.responseBody.FromJson<JsonMap>()!!
            } catch (e: Exception) {
                LoggerFactory.getLogger("ApiStory").error(e.message)
            }

            return null;
        }
}


/**
 * 每个人，有不同的测试实例
 */
@Document
@DbEntityGroup("dev")
@Cn("Api测试")
open class ApiExecTest : BaseMarkEntity() {
    var apiDefine = ApiDefine()
    var host = ""
    var authorization = ""
    var headers = StringMap()
    var parameters = StringMap()

    var status = 0
    var responseHeader = StringMap()
    var responseBody = ""
    var createBy = IdName();
}